package com.github.tvbox.osc.ui.fragment

import android.os.Bundle
import android.view.View
import android.view.animation.BounceInterpolator
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseQuickAdapter.RequestLoadMoreListener
import com.github.tvbox.osc.R
import com.github.tvbox.osc.base.BaseLazyFragment
import com.github.tvbox.osc.ui.activity.DetailActivityKt
import com.github.tvbox.osc.ui.activity.SearchActivity
import com.github.tvbox.osc.ui.adapter.GridAdapter
import com.github.tvbox.osc.ui.dialog.GridFilterDialog
import com.github.tvbox.osc.ui.tv.widget.LoadMoreView
import com.github.tvbox.osc.util.FastClickCheckUtil
import com.github.tvbox.osc.viewmodel.SourceViewModel
import com.owen.tvrecyclerview.widget.TvRecyclerView
import com.owen.tvrecyclerview.widget.TvRecyclerView.OnItemListener
import com.owen.tvrecyclerview.widget.V7GridLayoutManager
import io.github.source.media.bean.MediaBean
import io.github.source.media.bean.MediaCategory
import io.github.source.media.bean.MediaQuery
import io.github.source.media.bean.MediaResult

/**
 * @ClassName: GridFragmentKt
 * @Description: 展示媒体文件(这里用一句话描述这个类的作用)
 * @author: huangrongcai
 * @date: 2024/10/9
 *
 * @Copyright: 黄嵘才（HuangRc)
 */
class GridFragmentKt : BaseLazyFragment() {
    private var sortData: MediaCategory? = null
    private var mGridView: RecyclerView? = null
    private lateinit var sourceViewModel: SourceViewModel
    private var gridFilterDialog: GridFilterDialog? = null
    private var gridAdapter: GridAdapter? = null
    private var page = 1
    private var maxPage = 1
    private var isLoad = false
    private var isTop = true

    companion object {
        @JvmStatic
        fun newInstance(data: MediaCategory): GridFragmentKt {
            return GridFragmentKt().apply {
                this.setData(data)
            }
        }

        @JvmStatic
        fun newInstance(): GridFragmentKt {
            return GridFragmentKt().apply {
                // sortData = MediaCategory()
            }
        }
    }


    override fun getLayoutResID(): Int {
        return R.layout.fragment_grid
    }

    override fun onFragmentResume() {
        super.onFragmentResume()
    }

    fun setData(sortData: MediaCategory) {
        this.sortData = sortData
    }

    override fun init() {
        super.init()
        initViewModel()
    }

    override fun initData() {
        super.initData()
        initMediaData()
    }

    override fun initView() {
        super.initView()
        mGridView = findViewById(R.id.mGridView)
        mGridView?.setHasFixedSize(true)
        mGridView?.setLayoutManager(V7GridLayoutManager(mContext, if (isBaseOnWidth) 5 else 6))
//        mGridView?.setOnItemListener(createItemListener())
//        mGridView?.setOnInBorderKeyEventListener(createInBorderKeyEventListener())

        gridAdapter = GridAdapter()
        mGridView?.setAdapter(gridAdapter)

        gridAdapter?.setOnLoadMoreListener(createLoadMoreListener())
        gridAdapter?.setOnItemClickListener(createItemClickListener())
        gridAdapter?.setLoadMoreView(LoadMoreView())


    }

    private fun createLoadMoreListener(): RequestLoadMoreListener {
        return RequestLoadMoreListener {
            val query = obtainQuery()
            sourceViewModel.fetchMediaList(query)
        }
    }

    private fun createItemListener(): OnItemListener {
        return object : OnItemListener {
            override fun onItemPreSelected(parent: TvRecyclerView, itemView: View, position: Int) {
                itemView.animate().scaleX(1.0f).scaleY(1.0f).setDuration(300)
                    .setInterpolator(BounceInterpolator()).start()
            }

            override fun onItemSelected(parent: TvRecyclerView, itemView: View, position: Int) {
                itemView.animate().scaleX(1.05f).scaleY(1.05f).setDuration(300)
                    .setInterpolator(BounceInterpolator()).start()
            }

            override fun onItemClick(parent: TvRecyclerView, itemView: View, position: Int) {}
        }
    }

    private fun createInBorderKeyEventListener(): TvRecyclerView.OnInBorderKeyEventListener? {
        return TvRecyclerView.OnInBorderKeyEventListener { direction: Int, focused: View? ->
            if (direction == View.FOCUS_UP) {
            }
            false
        }
    }


    private fun createItemClickListener(): BaseQuickAdapter.OnItemClickListener? {
        return BaseQuickAdapter.OnItemClickListener { adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int ->
            FastClickCheckUtil.check(view)
            val video = gridAdapter?.data?.get(position)
            if (video != null) {
                val bundle = Bundle()
                bundle.putString("id", video.vodId)
                bundle.putString("sourceKey", video.siteKey)
                bundle.putString("title", video.vodName)
                if (video.vodId == null || video.vodId.isEmpty() || video.vodId.startsWith("msearch:")) {
                    jumpActivity(SearchActivity::class.java, bundle)
                } else {
                    jumpActivity(DetailActivityKt::class.java, bundle)
                }
            }
        }
    }

    private fun initViewModel() {
        sourceViewModel = ViewModelProvider(this)[SourceViewModel::class.java]
        sourceViewModel.MediaBeanResult?.observe(
            this
        ) { result: MediaResult<List<MediaBean>?>? ->
            setMediaResultData(result)
            if (page > maxPage) {
                gridAdapter?.loadMoreEnd()
            } else {
                gridAdapter?.loadMoreComplete()
            }
        }
    }

    private fun setMediaResultData(result: MediaResult<List<MediaBean>?>?) {
        if (result?.data?.isNotEmpty() == true) {
            showSuccess()
            if (isDataEmpty()) { //第一页（次）刷新
                isLoad = true
                gridAdapter?.setNewData(result.data)
            } else {
                gridAdapter?.addData(result.data!!)
            }
            page++
            maxPage = 999
        } else {
            if (isDataEmpty()) {
                showEmpty()
            } else {
                gridAdapter?.setEnableLoadMore(false)
            }
        }
    }

    private fun isDataEmpty(): Boolean {
        return gridAdapter?.data == null || gridAdapter?.data?.isEmpty() == true
    }

    fun isLoad(): Boolean {
        return isLoad
    }


    protected fun initMediaData() {
        showLoading()
        isLoad = false
        val query = obtainQuery()
        sourceViewModel.fetchMediaList(query)
    }

    fun obtainQuery(): MediaQuery? {
        val query = MediaQuery.obtain()
        if (sortData != null) {
            query.setId(sortData?.id)
        }
        query.page(page)
        return query
    }

    fun isTop(): Boolean {
        return isTop
    }

    fun scrollTop() {
        isTop = true
        mGridView?.scrollToPosition(0)
    }

    fun showFilter() {
        if (!sortData?.filters?.isEmpty()!! && gridFilterDialog == null) {
            gridFilterDialog = GridFilterDialog(mContext)
            gridFilterDialog?.setData(sortData)
            gridFilterDialog?.setOnDismiss(GridFilterDialog.Callback {
                page = 1
                initMediaData()
            })
        }
        if (gridFilterDialog != null) gridFilterDialog?.show()
    }

    /**
     * 开关过滤条件
     *
     * @param open
     */
    fun toggleFilter(open: Boolean) {
        if (open) showFilter() else hideFilter()
        mOpen = open
    }

    var mOpen = false

    fun hideFilter() {}

    fun canBack(): Boolean {
        //处理后退事件（按键后退，划动后退）
        //1.回到最顶
        if (!isTop) {
            scrollTop()
        }
        return false
    }

    fun goBack() {
        //处理后退事件（按键后退，划动后退）
    }
}